package com.ruoyi.eqmonitor;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class TestMqtt {

        public static void main(String[] args) {
            try {
                String broker = "tcp://localhost:1883";
                String clientId = "JavaClient";
                MqttClient sampleClient = new MqttClient(broker, clientId);
                MqttConnectOptions connOpts = new MqttConnectOptions();
                connOpts.setCleanSession(true);
                System.out.println("Connecting to broker: " + broker);
                sampleClient.connect(connOpts);
                System.out.println("Connected");
                String topic = "sampleTopic";
                String content = "Hello World! From MQTT";
                MqttMessage message = new MqttMessage(content.getBytes());
                message.setQos(2);
                message.setRetained(false);
                System.out.println("Publishing message: " + content);
                sampleClient.publish(topic, message);
                System.out.println("Message published");
                sampleClient.disconnect();
                System.out.println("Disconnected");
                System.exit(0);
            } catch (MqttException me) {
                System.out.println("reason " + me.getReasonCode());
                System.out.println("msg " + me.getMessage());
                System.out.println("loc " + me.getLocalizedMessage());
                System.out.println("cause " + me.getCause());
                System.out.println("exiting with 1");
                System.exit(1);
            }
    }
}
